package cn.donting.jme.swing;

import cn.donting.jme.expansion.attribute.ValueChangeListener;
import com.jme3.math.Vector3f;

import javax.swing.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class JVector3fTextField extends JComponent {

    private List<ValueChangeListener<Vector3f>> changeListenerList = new ArrayList<>();
    private JFloatTextField xTextField = new JFloatTextField();
    private JFloatTextField yTextField = new JFloatTextField();
    private JFloatTextField zTextField = new JFloatTextField();

    public JVector3fTextField() {
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        add(new JLabel("X:"));
        add(xTextField);
        add(new JLabel("Y:"));
        add(yTextField);
        add(new JLabel("Z:"));
        add(zTextField);

        xTextField.addValueChangeListener(this::change);
        yTextField.addValueChangeListener(this::change);
        zTextField.addValueChangeListener(this::change);
    }

    public Vector3f getValue() {
        return new Vector3f(
                xTextField.getValue().floatValue(),
                yTextField.getValue().floatValue(),
                zTextField.getValue().floatValue()
        );
    }

    public void setValue(Vector3f value) {
        xTextField.setValue(value.x);
        yTextField.setValue(value.y);
        zTextField.setValue(value.z);
    }

    public void addValueChangeListener(ValueChangeListener<Vector3f> listener) {
        this.changeListenerList.add(listener);
    }

    private void change(BigDecimal newValue) {
        for (ValueChangeListener<Vector3f> listener : this.changeListenerList) {
            listener.change(getValue());
        }
    }
}
